Plus One

Given a non-negative number represented as an array of digits, plus one to the number. </br> The digits are stored such that the most significant digit is at the head of the list.

题目大意:给定一个非负整数(以数组方式给出,各个位置为一位,最高位在第0位),加1后以数组形式返回结果

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/9
 */
public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0) return null;

        int len = digits.length;
        while ( --len >= 0) {
            if (len == 0 && digits[0] == 9) {
                int[] result = new int[digits.length + 1];
                result[0] = 1;
                return result;
            }
            if (digits[len] == 9) {
                digits[len] = 0;
            } else {
                ++digits[len];
                break;
            }
        }
        return digits;
    }
}
gzdaijie            updated 2016-05-10 00:56:01

results matching ""

    No results matching ""